package cn.edu.bit.cs;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class NotifierServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		
		String message = URLEncoder.encode("just for test", "UTF-8");

		try {
			URL url = new URL("https://fetionAPI.appspot.com/api/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("from=" + "13488810398");
            writer.write("&pw=" + "");
            writer.write("&to=" + "13488810398");
            writer.write("&msg=" + message);
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
            	resp.getWriter().println("ok " + connection.getResponseMessage());
            } else {
                // Server returned HTTP error code.
            	resp.getWriter().println(connection.getResponseMessage());
            }

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
